<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\goods\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Cache;
use think\Db;
use app\goods\model\Pricelevel as PricelevelModel;
use app\goods\model\PriceGroup as PriceGroupModel;
use app\goods\model\Price      as PriceModel;
use app\goods\model\Product    as ProductModel;

/**
 * 价格等级
 */
class Price extends Admin
{
    public function index(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $data_list = PricelevelModel::order('priceid DESC')->paginate();
           
        return ZBuilder::make('table')
        ->addColumns([ // 批量添加列
            ['pricename', '名称'],
            ['number', '编号'],
            ['code', 'code'],
            ['status', '状态' , 'status'],
            ['right_button', '操作', 'btn']
        ])
        ->setTableName('goods_price')
        ->setPrimaryKey('priceid')
        ->addRightButton('edit')
        ->addRightButton('delete')
        ->addTopButton('add')
        ->setRowList($data_list)
        ->fetch();
    }


    /**
    *新增
    */
    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = PricelevelModel::insert($data);
            if($result) {
                $this->success('新增成功');
            }else{
                $this->error('新增失败');
            }
        }


        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列            
            ['text', 'pricename', '名称'],
            ['text', 'number', '编号'],
            ['text', 'code', 'code'],
            ['radio', 'status' , '状态', '', ['0' => '禁用' ,'1' => '启用'], '1'],  
            
        ])
        ->layout(['pricename' => 6, 'number' => 6, 'code' => 6, 'status' => 6,])
        ->fetch();
    }

    /**
    *修改
    */
    public function edit($id = 0){
        if ($id === 0) return $this->error('缺少参数');

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = PricelevelModel::update($data);
            if($result) {
                $this->success('修改成功', cookie('__forward__'));
            }else{
                $this->error('修改失败');
            }
        }

        //详情
        $info      = PricelevelModel::where('priceid',$id)->find();

        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列
            ['hidden', 'priceid'],            
            ['text', 'pricename', '名称'],
            ['text', 'number', '编号'],
            ['text', 'code', 'code'],
            ['radio', 'status' , '状态', '', ['0' => '禁用' ,'1' => '启用'], '1'],  
            
        ])
        ->setFormData($info)
        ->layout(['pricename' => 6, 'number' => 6, 'code' => 6, 'status' => 6,])
        ->fetch();
    }


    /**
    *删除
    */
    public function delete($ids = 0){
        $id   = input('ids');
        $result = PricelevelModel::where(array('priceid' => $id))->delete();
        if($result){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function lists(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $data_list = PriceGroupModel::order('pricegroupid DESC')->paginate();
        foreach ($data_list as $key => $value) {
                   $filepath = PUBLIC_PATH.Db::name('admin_attachment')->where('id',$value['filename'])->value('path');
                   $data_list[$key]['filename'] = '<a href="'. $filepath.'"
                        data-toggle="tooltip" title="点击下载">
                        <img class="image" src="'.config('public_static_path').'admin/img/files/xlsx.png"></a>';
               }           
        return ZBuilder::make('table')
        ->addColumns([ // 批量添加列
            ['pricegroupname', '名称'],
            ['start_time', '生效日期', 'date'],
            ['end_time', '结束日期', 'date'],
            ['status', '状态' , 'status'],
            ['createname', '创建人'],
            ['create_time', '创建日期'],
            ['filename', '文件'],
            ['right_button', '操作', 'btn']
        ])
        ->setTableName('goods_pricegroup')
        ->setPrimaryKey('pricegroupid')
        ->addTopButton('enable', ['field' => 'status', 'title' => '启用'])
        ->addTopButton('disable', ['field' => 'status', 'title' => '禁用'])
        ->addTopButton('add',['title' => '导入','href' => url('leading')], true)
        ->addTopButton('custom', ['title' => '下载导入模板', 'icon' => 'fa fa-fw fa-download', 'href'=> url('downloadtpl',['name' => 'price.xlsx']), 'class' => 'btn btn-info'])
        ->setRowList($data_list)
        ->addRightButton('edit', ['href' => url('show',['id' => '__id__']), 'icon' => 'fa fa-fw fa-crosshairs', 'title' => '查看'])
        ->fetch();
    }

    public function leading(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['filename'])){
                $this->error('请上传文件');
            }
            $result = $this->validate($data, 'Price');
            if(true !== $result) return $this->error($result);

            $data['start_time']  = strtotime($data['start_time']);
            $data['end_time']    = strtotime($data['end_time']);
            $data['create_time'] = time();
            if($data['status'] == 1){
                PriceGroupModel::where('status','1')->update(['status' => '0']);
            }

            $pricegroupid = PriceGroupModel::insertGetId($data);

            $file = Db::name('admin_attachment')->where('id', $data['filename'])->value('path');
            $filetmpname = $_SERVER['DOCUMENT_ROOT'] . '/public/' . $file;
            
            import('util.PHPExcel', EXTEND_PATH, '.class.php');
            $PHPExcel = new \PHPExcel();
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            if(!$PHPReader->canRead($filetmpname)){
                $PHPReader = new \PHPExcel_Reader_Excel5();
                if(!$PHPReader->canRead($filetmpname)){
                    $PHPReader = new \PHPExcel_Reader_CSV();
                    if(!$PHPReader->canRead($filetmpname)){
                        $this->error("no Excel");
                    }
                }
            }

            $PHPExcel = $PHPReader->load($filetmpname);
            $ids = array();
            $memberset=array();
            $sheet = $PHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $errmsg = '';
            $result = false;
            $p = 1;
            $add_data['pricegroupid'] = $pricegroupid;
            for ($row = 2; $row <= $highestRow; $row++){
                $add_data['levelcode'] = $sheet->getCell('A'.$row)->getValue();
                $add_data['skuno']     = $sheet->getCell('B'.$row)->getValue();
                $add_data['commision'] = $sheet->getCell('C'.$row)->getValue();
                $add_data['money']     = $sheet->getCell('D'.$row)->getValue();
                $add_data['levelid']   = PricelevelModel::where('code',$add_data['levelcode'])->value('priceid');
                $add_data['skuid']     = ProductModel::where('goodsno',$add_data['skuno'])->value('goodsid');
                if(empty($add_data['levelid']) || empty($add_data['skuid']) || empty($add_data['money'])){
                    $errmsg .= '第'.$row.'行基本信息信息未填<br/>';
                }else{
                    $result = PriceModel::insert($add_data);
                }
                
            }

            if($result){
                $this->success('上传成功', null, ['_parent_reload' => 1]);
            }else{
                $this->error("$errmsg");
            }

        }else{
            return ZBuilder::make('form')
            ->addFormItems([ // 批量添加列          
                ['text', 'pricegroupname', '名称'],
                ['text', 'createname', '创建人'],
                ['date', 'start_time', '生效日期'],
                ['date', 'end_time', '结束日期'],
                ['radio', 'status' , '状态', '', ['0' => '禁用' ,'1' => '启用'], '0'],
                ['importfile', 'filename', '文件'],  
                
            ])
            ->layout(['pricegroupname' => 6, 'createname' => 6, 'start_time' => 6, 'end_time' => 6, 'status' => 6, 'filename' => 6])
            ->fetch();
            }
    }

    //下载模板
    public function downloadtpl($name = '') {
        $file=$_SERVER['DOCUMENT_ROOT']. "/public/uploads/template/".$name;
        if(is_file($file)) {
            header("Content-Type: application/force-download");
            header("Content-Disposition: attachment; filename=".basename($file));
            readfile($file);
            exit;
        }else{
            $this->error('文件不存在！');
        }
    }


    //明细
    public function show($id = 0){
        $url = cookie('__forward__');
        $where = $this->getMap();
        $where['pricegroupid'] = $id;
        $data_list = PriceModel::where($where)->paginate();
        return ZBuilder::make('table')
        ->addColumns([ // 批量添加列
            ['skuno', 'SKU编码'],
            ['levelcode', '等级CODE'],
            ['commision', '佣金比率'],
            ['money', '价格'],
        ])
        ->addFilter('skuno,levelcode,commision,money')
        ->setTableName('goods_price')
        ->setPrimaryKey('priceid')
        ->addTopButton('add',['title' => '返回','href' => $url])
        ->setRowList($data_list)
        ->fetch();

    }

    public function enable($data = []){
        $data = input('');
        if(count($data['ids']) > 1){
            $this->error('只能允许启用一条');
        }

        PriceGroupModel::where('status','1')->update(['status' => '0']);
        $result = PriceGroupModel::where('pricegroupid', $data['ids']['0'])->update(['status' => '1']);
        if($result){
            $this->success('启用成功');
        }else{
            $this->error('启用失败');
        }
    }


   
}
